package com.example.gpio;// MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {


    private final String GPIO_PATH = "/sys/devices/platform/gpio_ctrl/SUB_EN3";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button buttonOn = findViewById(R.id.button_on);
        Button buttonOff = findViewById(R.id.button_off);
        // 创建缩放动画对象
        ScaleAnimation scaleAnimation = new ScaleAnimation(
                0.9f, 1.1f, // X轴起始缩放比例
                0.9f, 1.1f, // Y轴起始缩放比例
                android.view.animation.Animation.RELATIVE_TO_SELF, 0.5f, // 动画中心点X
                android.view.animation.Animation.RELATIVE_TO_SELF, 0.5f  // 动画中心点Y
        );
        scaleAnimation.setDuration(150); // 动画时长
        scaleAnimation.setRepeatCount(0); // 不重复
        scaleAnimation.setRepeatMode(android.view.animation.Animation.REVERSE);

        // 设置按钮点击事件并启动动画
        buttonOn.setOnClickListener(v -> {
            buttonOn.startAnimation(scaleAnimation);
            controlGpio(0); // 调用控制GPIO的逻辑
        });

        buttonOff.setOnClickListener(v -> {
            buttonOff.startAnimation(scaleAnimation);
            controlGpio(1); // 调用控制GPIO的逻辑
        });

        // 导出GPIO4
//        exportGpio("4");
//        setGpioDirection("4", "out");
    }

    private void controlGpio(int value) {
        try {
            String command = value == 1 ? "1" : "0";
            writeToFile(GPIO_PATH, command);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    private void exportGpio(String gpioNumber) {
//        writeToFile(GPIO_PATH + "export", gpioNumber);
//    }
//
//    private void setGpioDirection(String gpioNumber, String direction) {
//        writeToFile(GPIO_PATH + "gpio" + gpioNumber + "/direction", direction);
//    }

    private void writeToFile(String path, String value) {
        try (FileOutputStream fos = new FileOutputStream(new File(path))) {
            fos.write(value.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}